#!usr/bin/env python
# -*- coding:utf-8 _*-
"""
# author: 小菠萝测试笔记
# blog:  https://www.cnblogs.com/poloyy/
# time: 2021/10/21 1:13 下午
# file: request_utils.py
"""
from typing import Dict, Tuple, Union

from fastapi import HTTPException, status
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel
from sqlalchemy.orm import Session

from app.crud import CRUDBase
from app.schemas import Page


def create_data(obj_in: BaseModel, db: Session, obj: CRUDBase, name: str) -> Dict:
    if obj.get_first_by_name(db, name=obj_in.name):
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST, detail=f"{name} name 不可重复"
        )
    db_data = obj.create(db, obj_in=obj_in)
    return {
        "code": 200,
        "msg": "创建成功",
        "id": db_data.id,
        f"{name}": jsonable_encoder(db_data),
    }


def get_list_data(
    page: Page, db: Session, obj: CRUDBase, result: str = ""
) -> Union[Dict, Tuple]:
    db_list = obj.get_multi_by_name(
        db, skip=page.size * (page.page - 1), limit=page.size, name=page.name
    )
    total = obj.get_total_by_name(db, name=page.name)
    if result:
        return {
            f"{result}": db_list,
            "total": total,
            "page": page.page,
            "size": page.size,
        }
    else:
        return db_list, total


def update_data(obj_in: BaseModel, db: Session, obj: CRUDBase, name: str) -> Dict:
    db_data = obj.get(db, id=obj_in.id)
    if not db_data:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"{name} 不存在")

    db_check = obj.get_first_by_name(db, name=obj_in.name)
    if db_check and db_check.id != db_data.id:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST, detail=f"{name} name 不可重复"
        )

    res = obj.update(db, db_obj=db_data, obj_in=obj_in)

    return {"code": 200, "msg": "更新成功", "id": res.id}


def delete_data(id: int, db: Session, obj: CRUDBase, name: str) -> Dict:
    db_data = obj.delete(db, id=id)
    if not db_data:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"{name} 不存在")
    return {"code": 200, "msg": "删除成功", "id": db_data.id}
